<?php


namespace app\admin\business;


use think\Exception;
use app\admin\model\AdminUser as AdminUserModel;

class AdminUser {
    public $adminUserObj = null;

    public function __construct() {
        $this->adminUserObj = new AdminUserModel();
    }

    public function login($data) {

        $adminUser = $this->getAdminUserByUsername($data['username']);
        if (!$adminUser) {
            return show(config('status.error'), '不存在该用户');
        }
        if ($adminUser['password'] != md5($data['password'] . config('admin.md5_poke'))) {
            throw new Exception("密码不正确");
        }

        $updateData = [
            "last_login_time" => time(),
            "update_time" => time(),
            "last_login_ip" => request()->ip(),
        ];
        $res = $this->adminUserObj->updateById($adminUser['id'], $updateData);
        if (empty($res)) {
            throw new Exception("登录失败");
        }

        session(config('admin.session_admin'), $adminUser);
        return true;
    }

    public function getAdminUserByUsername($username) {
        $adminUser = $this->adminUserObj->getAdminUserByUsername($username);
        if (empty($adminUser) || $adminUser->status != config("status.mysql.table_normal")) {
            return [];
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}